const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const params = require('common-params');

const authorizationKey = params.authorization;

const httpGet = function(url, data, success, fail, complete) {

  const token = wx.getStorageSync(authorizationKey);

  const header = {};
  data = data || {};
  // data[shopidKey] = shopid;
  // data[storeidKey] = storeid;
  if (token) {
    header[authorizationKey] = token;
  }
  // if (tableid) {
  //   data[tableidKey] = tableid;
  // };
  wx.showNavigationBarLoading();
  return wx.request({
    url: params.apiHost + url,
    method: 'GET',
    data: data,
    header: header,
    success: function(res) {
      if (res.statusCode === 200 && success) {
        success(res.data);
      } else if (res.statusCode === 401) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '服务器开小差了！',
        })
      };
    },
    fail: function(err) {
      wx.showToast({
        icon: 'none',
        title: '服务器开小差了！',
      })
    },
    complete: function() {
      wx.hideNavigationBarLoading();
      if (complete) {
        complete();
      };
    }
  })
}

const httpPost = function(url, data, success, fail, complete) {

  const token = wx.getStorageSync(authorizationKey);

  const header = {
    'content-type': 'application/x-www-form-urlencoded'
  };
  data = data || {};
  // data[shopidKey] = shopid;
  // data[storeidKey] = storeid;
  if (token) {
    header[authorizationKey] = token;
  };
  // if (tableid) {
  //   data[tableidKey] = tableid;
  // };
  wx.showNavigationBarLoading();
  return wx.request({
    url: params.apiHost + url,
    method: 'POST',
    data: data,
    header: header,
    success: function(res) {
      if (res.statusCode === 200 && success) {
        success(res.data);
      } else if (res.statusCode === 401) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '服务器开小差了！',
        })
      };
    },
    fail: function(err) {
      wx.showToast({
        icon: 'none',
        title: '服务器开小差了！',
      })
    },
    complete: function() {
      wx.hideNavigationBarLoading();
      if (complete) {
        complete();
      };
    }
  })
}

//必须放在最后且将需要的方法和参数命名
module.exports = {
  httpPost: httpPost,
  httpGet: httpGet,
  authorizationKey: authorizationKey,
  formatTime: formatTime
}